import { loadEnv } from "vite"

/**
 * @description: 根据.env 文件设置的代理字段转换成vite.config.server.proxy 识别的字段信息
 * @param { string } .env.development 配置文件里的 VITE_PROXY 字段
 * @return { Object }
 */
export const getViteProxy = (VITE_PROXY) => {
  if (!VITE_PROXY) return
  let proxys 
  
  try {
    proxys = JSON.parse(VITE_PROXY)
  } catch {
    console.error(".env.development VITE_PROXY 解析失败")
    process.exit()
  }

  const result = {}

  for (const [prefix, target] of proxys) {
    result[prefix] = {
      target,
      changeOrigin: true,
      secure: false,
    }
  }

  return result
}

export const getViteEnv = (mode) => {
  return loadEnv(mode, process.cwd())
}
